package com.vm.fragment;

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.vm.activity.ActiveActivity;
import com.vm.adapter.CategoryGameListAdapter;
import com.vm.commons.VMConst;
import com.vm.model.AppType;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyVolley;
import com.wwtscapp.apk.R;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("InflateParams")
public class CategoryGameFragment extends BaseFragment {
	protected static final String TAG = null;
	private RequestQueue mQueue;
	private List<AppType> listapptypes;
	private View view;

	/** 标志位，标志已经初始化完成 */
	private boolean isPrepared;
	/** 是否已被加载过一次，第二次就不再去请求数据了 */
	private boolean mHasLoadedOnce;

	TextView tv_hot_game;
	TextView tv_hot_online;
	TextView tv_latest_game;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		Log.i("CategoryGameFragment", "onCreateView");

		if (view == null) {
			view = inflater.inflate(R.layout.category_game_list, null);
		} else {
			// 缓存的rootView需要判断是否已经被加过parent
			// 如果有parent需要从parent删除
			ViewGroup parent = (ViewGroup) view.getParent();
			if (parent != null) {
				parent.removeView(view);
			}
		}
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.e(TAG, "Game");
		mQueue = MyVolley.getRequestQueue();

		isPrepared = true;
		lazyLoad();

	}

	public void initView() {
		tv_hot_game = (TextView) view.findViewById(R.id.tv_hot_game);
		tv_hot_online = (TextView) view.findViewById(R.id.tv_hot_online);
		tv_latest_game = (TextView) view.findViewById(R.id.tv_latest_game);

		tv_hot_game.setOnClickListener(textClickListener);
		tv_hot_online.setOnClickListener(textClickListener);
		tv_latest_game.setOnClickListener(textClickListener);
	}

	OnClickListener textClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent;
			String activeType = null;
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.tv_hot_game:
				intent = new Intent(getActivity(), ActiveActivity.class);
				activeType = VMConst.ActiveType.getHotGame.toString();
				intent.putExtra("activeType", activeType);
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.热门游戏.toString());
				startActivityForResult(intent, 10);
				break;
			case R.id.tv_hot_online:
				intent = new Intent(getActivity(), ActiveActivity.class);
				intent.putExtra("activeType",
						VMConst.ActiveType.getHotOnline.toString());
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.精选网游.toString());
				startActivityForResult(intent, 10);
				break;
			case R.id.tv_latest_game:
				intent = new Intent(getActivity(), ActiveActivity.class);
				intent.putExtra("activeType",
						VMConst.ActiveType.getLatestGame.toString());
				intent.putExtra("currentType",
						VMConst.ActiveTypeName.最新游戏.toString());
				startActivityForResult(intent, 10);
				break;

			default:
				break;
			}

		}
	};

	private void initData() {
		try {
			listapptypes = new ArrayList<AppType>();
			JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(
					VMConst.REQUEST_URL + "getAllGameType", new Listener<JSONArray>() {

						@Override
						public void onResponse(JSONArray arg0) {
							// TODO Auto-generated method stub
							for (int i = 0; i < arg0.length(); i++) {
								try {
									JSONObject jsonObject = arg0
											.getJSONObject(i);
									String s = jsonObject.toString();
									Log.i(TAG, s);
									AppType apptype = JsonUtils.jsonToBean(
											jsonObject, AppType.class);
									if (apptype != null) {
										listapptypes.add(apptype);
									}
								} catch (JSONException e) {
									e.printStackTrace();
								}
							}
							CategoryGameListAdapter myAdapter = new CategoryGameListAdapter(
									getActivity(), listapptypes);
							ListView listview = (ListView) view
									.findViewById(R.id.listview);
							listview.setAdapter(myAdapter);
						}

					}, new Response.ErrorListener() {
						public void onErrorResponse(VolleyError error) {
							Log.e(TAG, error.getMessage(), error);
						}
					});
			mQueue.add(jsonObjectRequest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void lazyLoad() {
		// TODO Auto-generated method stub
		if (!isPrepared || !isVisible || mHasLoadedOnce) {
			return;
		}

		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// 显示加载进度对话框
				UIHelper.showDialogForLoading(getActivity(), "正在加载...", true);
				mainHandler.sendMessage(new Message());
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				try {
					Thread.sleep(300);
					initData();
					// 在这里添加调用接口获取数据的代码
					// doSomething()
				} catch (Exception e) {
					e.printStackTrace();
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean isSuccess) {
				if (isSuccess) {
					// 加载成功
					// setView();
					mHasLoadedOnce = true;
				} else {
					// 加载失败
				}
				// 关闭对话框
				UIHelper.hideDialogForLoading();
			}
		}.execute();
	}

	private Handler mainHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {

			initView();
		};
	};

}
